package com.surveycomp.servlets;

import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.mail.MailService.Message;
import com.google.appengine.api.mail.MailServiceFactory;
import com.surverycomp.models.Challenge;
import com.surverycomp.models.Event;
import com.surveycomp.datastore.PMF;

public class CreateEventServlet extends BaseServlet {
	private static final long serialVersionUID = -5427588372394003371L;

	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {

		Event event;
		try {
			event = createEvent(req);
		} catch (ParseException e) {
			resp.sendRedirect("");
			return;
		}

		if (validateEvent(event)) {
			HttpSession session = req.getSession(true);
			PersistenceManager pm = PMF.get().getPersistenceManager();
			List<Challenge> challenges = null;
			try {
				Message msg = new Message("allan.stisen@gmail.com",
						"allan.stisen@gmail.com", "Welcome", "Welcome");
				MailServiceFactory.getMailService().send(msg);
				challenges = createChallenges(req);
				pm.makePersistentAll(challenges);

				List<Key> challengeKeys = new ArrayList<Key>(challenges.size());

				for (Challenge c : challenges) {
					challengeKeys.add(c.getKey());
				}
				event.setChallengeKeys(challengeKeys);

				event = pm.makePersistent(event);
				System.out.println(challenges);
			} finally {
				pm.close();
				session.setAttribute("event", event);
				session.setAttribute("challenges", challenges);
				resp.sendRedirect("receipt.jsp");
			}
		} else {
			resp.sendRedirect("");
		}
	}

	protected Event createEvent(HttpServletRequest req) throws ParseException {
		Event event = new Event(req);
		return event;
	}

	protected List<Challenge> createChallenges(HttpServletRequest req) {
		int counter = ServletUtils.getInt("counter", req);
		List<Challenge> challenges = new ArrayList<Challenge>(counter);

		for (int i = 1; i <= counter; i++) {
			String challenge = "challenge-" + i;
			Challenge c = new Challenge(challenge, req);

			challenges.add(c);
		}
		return challenges;
	}

	private boolean validateEvent(Event event) {
		return event.getDatefrom() != 0 && event.getDateTo() != 0
				&& event.getDateTo() > event.getDatefrom()
				&& event.getName() != null && event.getName().length() >= 3;
	}
}
